import os, cv2, oss2
from uuid import uuid4
import urllib.request
import numpy as np
from PIL import Image
from config import recipe_config
import sys


def build_code():
    """
    创建数据编码
    :return: 返回数据编码
    """
    uid = str(uuid4())
    return ''.join(uid.split('-'))


def down(url):
    """
    下载网页
    :param url: 网页地址
    :return: 返回网页数据
    """
    return urllib.request.urlopen(url).read()


def downloadImg(img_url, file_path):
    """
    下载网络图片到本地
    :param img_url: 图片链接
    :param file_path: 本地存储地址
    :return:
    """
    try:
        # 是否有这个路径
        if not os.path.exists(file_path):
            # 创建路径
            os.makedirs(file_path)
            # 获得图片后缀
        file_name = os.path.basename(img_url)
        # 拼接图片名（包含路径）
        filename = '{}{}{}'.format(file_path, os.sep, file_name)
        # 下载图片，并保存到文件夹中
        urllib.request.urlretrieve(img_url, filename=filename)
        return filename
    except IOError as e:
        print("IOError")
    except Exception as e:
        print("Exception")


def removeWatermark(img_url):
    """
    去除图片水印
    :param img_url: 图片地址
    :return: 去除水印后的图片本地链接
    """
    try:

        path = img_url
        file_suffix = os.path.splitext(path)[1]
        newPath = path.replace(file_suffix, "_new" + file_suffix)
        img = cv2.imread(path, 1)
        hight, width, depth = img.shape[0:3]

        # 截取
        cropped = img[int(hight * 0.8):hight, int(width * 0.7):width]  # 裁剪坐标为[y0:y1, x0:x1]
        cv2.imwrite(newPath, cropped)
        imgSY = cv2.imread(newPath, 1)

        # 图片二值化处理，把[200,200,200]-[250,250,250]以外的颜色变成0
        thresh = cv2.inRange(imgSY, np.array([200, 200, 200]), np.array([250, 250, 250]))
        # 创建形状和尺寸的结构元素
        kernel = np.ones((3, 3), np.uint8)
        # 扩展待修复区域
        hi_mask = cv2.dilate(thresh, kernel, iterations=10)
        specular = cv2.inpaint(imgSY, hi_mask, 5, flags=cv2.INPAINT_TELEA)
        cv2.imwrite(newPath, specular)

        # 覆盖图片
        imgSY = Image.open(newPath)
        img = Image.open(path)
        img.paste(imgSY, (int(width * 0.7), int(hight * 0.8), width, hight))
        img.save(newPath)
        return newPath
    except IOError as e:
        print("IOError")
    except Exception as e:
        print("Exception")


def upload_aliyun_oss(file_path, object_path):
    try:
        # 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        auth = oss2.Auth(recipe_config.ALI_OSS_ACCESS_KEY_ID, recipe_config.ALI_OSS_ACCESS_KEY_SECRET)
        # yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        # 填写Bucket名称。
        bucket = oss2.Bucket(auth, 'https://'+recipe_config.ALI_OSS_ENDPOINT, recipe_config.ALI_OSS_BUCKET)
        bucket.put_object_from_file(object_path, file_path)
        res = r'https://'+recipe_config.ALI_OSS_BUCKET+'.'+recipe_config.ALI_OSS_ENDPOINT+'/' + object_path
        print(res)
        return res
    except Exception as e:
        print("Exception", e)


def write2file(path, recipe):
    """
    数据写入到文件
    :param path:
    :param recipe:
    :return:
    """
    f = open(path, 'a')
    f.write('\n' + recipe)
    f.close()
